/**
 * 简化的图标管理工具
 * 移除复杂的预加载和缓存机制，采用简单直接的导入方式
 */

// 项目中实际使用的图标列表
const USED_ICONS = [
  "Plus",
  "User", 
  "Lock",
  "Check",
  "Clock",
  "Edit",
  "ArrowLeft",
  "ArrowRight",
  "ArrowUp",
  "ArrowDown",
  "VideoPlay",
  "Upload",
  "Timer",
  "DataAnalysis",
  "TrendCharts",
  "Loading",
  "HomeFilled",
  "Expand",
  "Fold",
  "Monitor",
  "ChatDotRound",
  "Document",
  "Tools",
  "Camera",
  "Message",
  "Phone",
  "Location",
  "Key",
  "Link",
  "Sunny",
  "Moon",
];

// 图标缓存
const iconCache = new Map();

/**
 * 动态加载图标组件
 * @param {string} iconName - 图标名称
 * @returns {Promise<Component>} - 图标组件
 */
export async function loadIcon(iconName) {
  // 检查缓存
  if (iconCache.has(iconName)) {
    return iconCache.get(iconName);
  }

  // 检查是否为已知图标
  if (!USED_ICONS.includes(iconName)) {
    console.warn(`未知图标: ${iconName}`);
    return null;
  }

  try {
    // 动态导入图标
    const iconModule = await import("@element-plus/icons-vue");
    const IconComponent = iconModule[iconName];

    if (IconComponent) {
      iconCache.set(iconName, IconComponent);
      return IconComponent;
    }
    
    throw new Error(`图标 ${iconName} 不存在`);
  } catch (error) {
    console.error(`图标加载失败: ${iconName}`, error);
    return null;
  }
}

/**
 * 注册核心图标到Vue应用
 * @param {App} app - Vue应用实例
 */
export async function registerCoreIcons(app) {
  const coreIcons = ["User", "Lock", "HomeFilled", "ArrowRight", "Loading", "Sunny", "Moon"];
  
  for (const iconName of coreIcons) {
    try {
      const IconComponent = await loadIcon(iconName);
      if (IconComponent) {
        app.component(iconName, IconComponent);
      }
    } catch (error) {
      console.error(`注册图标失败: ${iconName}`, error);
    }
  }
}

/**
 * 初始化图标系统
 * @param {App} app - Vue应用实例
 */
export async function initIconSystem(app) {
  try {
    await registerCoreIcons(app);
  } catch (error) {
    console.error("图标系统初始化失败:", error);
  }
}

// 向后兼容的iconManager对象
export const iconManager = {
  loadIcon,
};